package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.PlanManage;
import com.isunland.managesystem.entity.PlanManageProgress;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.io.File;
import java.util.Date;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  日程进展详情
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/4/27 15:50
 */
public class PlanManageProgressDetailFragment extends BaseFragment {
  protected static final String EXTRA_VALUE =
      PlanManageProgressDetailActivity.class.getSimpleName() + "EXTRA_VALUE";
  protected static final String EXTRA_PROGRESSVALUE =
      PlanManageProgressDetailActivity.class.getSimpleName() + "EXTRA_PROGRESSVALUE";
  @BindView(R.id.et_plantitle) TextView etPlantitle;
  @BindView(R.id.tv_excname) TextView tvExcname;
  @BindView(R.id.tv_projectname) TextView tvProjectname;
  @BindView(R.id.tv_planStartTime) TextView tvPlanStartTime;
  @BindView(R.id.tv_planEndTime) TextView tvPlanEndTime;
  @BindView(R.id.tv_corname) TextView tvCorname;
  @BindView(R.id.et_planContentDesc) TextView etPlanContentDesc;
  @BindView(R.id.tv_taskvisibility) TextView tvTaskvisibility;
  @BindView(R.id.tv_filepath) TextView tvFilepath;
  @BindView(R.id.et_planProgressDesc) EditText etPlanProgressDesc;
  @BindView(R.id.cb_isFinish) CheckBox cbIsFinish;
  @BindView(R.id.et_finishPercent) EditText etFinishPercent;
  @BindView(R.id.tv_attentPerson) TextView tvAttentPerson;
  @BindView(R.id.tv_progressfilepath) TextView tvProgressfilepath;
  @BindView(R.id.iv_progressfilepath) ImageView ivProgressfilepath;
  @BindView(R.id.ll_finishProcess) LinearLayout llFinishProcess;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;

  private PlanManage mContent;
  private PlanManageProgress progressContent;
  private final int REQUSET_PERSON = 0;
  private final int REQUSET_CHOOSE = 3;
  private String mId;
  private String filepath;
  private String staffcode;
  private String staffname;
  private CurrentUser mUser;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.planProgress);
    mContent = (PlanManage) getArguments().getSerializable(EXTRA_VALUE);
    progressContent = (PlanManageProgress) getArguments().getSerializable(EXTRA_PROGRESSVALUE);
    mId = UUID.randomUUID().toString();
    filepath = "";
    mUser = CurrentUser.newInstance(getActivity());
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (progressContent == null) {
      //添加
      inflater.inflate(R.menu.menu_confirm, menu);
    } else {
      //详情
      inflater.inflate(R.menu.menu_delete, menu);
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_plan_manage_detail, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_confirm:
        //保存
        if (isComplete()) {
          volleyPostSave();
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        volleyPostDel();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private boolean isComplete() {
    if (TextUtils.isEmpty(etFinishPercent.getText().toString()) || TextUtils.isEmpty(
        etPlanProgressDesc.getText().toString())) {
      ToastUtil.show(R.string.complete_hint);
      return false;
    } else {
      // 对输入完成度进行校验
      String completePercent = etFinishPercent.getText().toString();
      int percent = Integer.parseInt(completePercent);
      if (percent < 0 || percent > 100) {
        Toast.makeText(getActivity(), R.string.finishPercentError, Toast.LENGTH_SHORT).show();
        return false;
      }
      //如果未完成，完成度不能填写100
      String finishDegree = etFinishPercent.getText().toString().trim();
      int degree = Integer.parseInt(finishDegree);
      if (!cbIsFinish.isChecked() && degree == 100) {
        ToastUtil.show(R.string.chooseBrforeHandr);
        return false;
      }
      return true;
    }
  }

  private void bindData() {
    llFinishProcess.setVisibility(View.VISIBLE);
    //详情
    etPlantitle.setText(mContent.getPlantitle());
    tvExcname.setText(mContent.getExcname());
    tvProjectname.setText(mContent.getProjectname());
    tvPlanStartTime.setText(mContent.getPlanStartTime());
    etPlanContentDesc.setText(mContent.getPlanContentDesc());
    tvPlanEndTime.setText(mContent.getPlanEndTime());
    tvCorname.setText(mContent.getCorname());
    tvTaskvisibility.setText(mContent.getTaskvisibility());
    tvFilepath.setText(FileUtil.getFileNameByFilePath(mContent.getFilepath()));

    if (progressContent != null) {
      //日程进展详情
      etPlanProgressDesc.setText(progressContent.getExcDesc());//进展描述
      cbIsFinish.setChecked("已完成".equals(progressContent.getIfend()) ? true : false);//是否完成
      etFinishPercent.setText(String.format("%s%%",
          progressContent.getComprate() != null ? progressContent.getComprate() : 0));//完成度
      tvAttentPerson.setText(progressContent.getStaffname());
      tvProgressfilepath.setText(FileUtil.getFileNameByFilePath(progressContent.getFilepath()));
      tvRegStaffName.setText(progressContent.getRegStaffName());
      tvRegDate.setText(progressContent.getRegDate());

      etPlanProgressDesc.setEnabled(false);
      cbIsFinish.setEnabled(false);
      etFinishPercent.setEnabled(false);
      tvAttentPerson.setEnabled(false);
      ivProgressfilepath.setVisibility(View.GONE);
    } else {
      //添加: 当前登录人(负责人和参与人都可以填写【添加进展】，但是参与人不允许更改进度和是否完成两个属性)
      tvRegStaffName.setText(mUser.getRealName());
      tvRegDate.setText(MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE));
      cbIsFinish.setChecked("已完成".equals(mContent.getIfend()) ? true : false);//是否完成
      etFinishPercent.setText(mContent.getComprate());//完成度
      if (mContent.getExcjobno().equalsIgnoreCase(mUser.getJobNumber())) {
        cbIsFinish.setEnabled(true);
        etFinishPercent.setEnabled(true);
      } else {
        cbIsFinish.setEnabled(false);
        etFinishPercent.setEnabled(false);
      }
    }
    cbIsFinish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) {
        if (isCheck) {
          //完成
          etFinishPercent.setText("100");
          etFinishPercent.setEnabled(false);
        } else {
          etFinishPercent.setEnabled(true);
          etFinishPercent.setText("0");
        }
      }
    });
  }

  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_PROGRESS_ADD);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("mainid", mContent.getId());
    params.put("id", mId);
    params.put("excDesc", etPlanProgressDesc.getText().toString());
    if (cbIsFinish.isChecked()) {
      params.put("ifend", "1");//完成
    } else {
      params.put("ifend", "0");//未完成
    }
    params.put("comprate", etFinishPercent.getText().toString());
    params.put("excjobno", mContent.getExcdeptjobno());
    params.put("excname", mContent.getExcname());
    params.put("excdeptname", mContent.getExcdeptname());
    params.put("staffcode", staffcode);
    params.put("staffname", staffname);
    params.put("filepath", filepath);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  private void volleyPostDel() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_PROGRESS_DELETE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", progressContent.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  public VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
          if (message != null && SuccessMessage.SUCCESS.equalsIgnoreCase(message.getResult())) {
            ToastUtil.show(message.getMessage());
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else if (message != null && SuccessMessage.FAILURE.equalsIgnoreCase(
              message.getResult())) {
            ToastUtil.show(message.getMessage());
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  @OnClick({
      R.id.tv_filepath, R.id.tv_attentPerson, R.id.iv_progressfilepath, R.id.tv_progressfilepath
  }) public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_filepath:
        //附件下载
        if (mContent != null && !TextUtils.isEmpty(mContent.getFilepath())) {
          showDialog(mContent.getFilepath());
        }
        break;
      case R.id.tv_attentPerson:
        //人员多选
        Intent person = new Intent(getActivity(), SearchPersonMultipleActicity.class);
        person.putExtra(SearchPersonMultipleFragment.EXTRA_FROM,
            SearchPersonMultipleFragment.VALUE_COMMON);
        startActivityForResult(person, REQUSET_PERSON);
        break;
      case R.id.iv_progressfilepath:
        //附件上传
        //showDialog(REQUSET_CHOOSE);
        chooseFile(REQUSET_CHOOSE);
        break;
      case R.id.tv_progressfilepath:
        //附件下载
        if (progressContent != null && !TextUtils.isEmpty(progressContent.getFilepath())) {
          showDialog(progressContent.getFilepath());
        }
        break;
    }
  }

  private void showDialog(String serverPath) {

    DialogFragment dialog = ExtraDownLoadDialogFragment.newInstance("", serverPath);
    FragmentManager fm = getFragmentManager();
    dialog.setTargetFragment(PlanManageProgressDetailFragment.this, 0);
    dialog.show(fm, "");
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;

    int REQUSET_UPLOAD = 1;
    if (requestCode == REQUSET_CHOOSE) {
      FileUploadDialgFragment dialog =
          FileUploadDialgFragment.newInstance(getFile(data), mId, "plancp.r_plan_exc_other", true);

      //String filePath=data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_RESULT);
      //FileUploadDialgFragment dialog =
      //    FileUploadDialgFragment.newInstance(filePath, mContent.getId(),
      //        "imsifwj.wj_erp_o_enterpriseforum_main", true);
      dialog.setTargetFragment(this, REQUSET_UPLOAD);
      dialog.show(mActivity.getSupportFragmentManager(), "");
    }
    if (requestCode == REQUSET_UPLOAD) {
      filepath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      tvProgressfilepath.setText(FileUtil.getFileNameByFilePath(filepath));
    }
    int REQUSET_DOWNLOAD = 2;
    if (requestCode == REQUSET_DOWNLOAD) {

    }
    if (requestCode == REQUSET_PERSON) {

      staffcode = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_JOB);
      staffname = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_NAME);
      tvAttentPerson.setText(staffname);
    }
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }

  public static PlanManageProgressDetailFragment newInstance(PlanManage content,
      PlanManageProgress progressContent) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_VALUE, content);
    args.putSerializable(EXTRA_PROGRESSVALUE, progressContent);
    PlanManageProgressDetailFragment fragment = new PlanManageProgressDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}

